#include <iostream>
#include <sys/types.h>
#include <string>
#include <sys/socket.h>
#include <cstring>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define BUF_SIZE 64

void Usage(const std::string& proc)
{
    std::cout << "Usage error! \n\t" << proc << "serverIP serverPort" << std::endl;
}

// ./client serverIP serverPort
int main(int argc, const char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverIP = argv[1]; // 服务器内网IP
    uint16_t serverPort = std::stoi(argv[2]);

    // 1. 创建UDP套接字(文件信息--栈上)
    int sfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }


    // 2. 与服务器进行通信

    // 填充目标主机的socket信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverPort);
    server.sin_addr.s_addr = inet_addr(serverIP.c_str());
    socklen_t len = sizeof(struct sockaddr_in);

    std::string message;
    char buffer[BUF_SIZE];
    while(true)
    {
        std::cout << "Please input message# ";
        std::getline(std::cin, message);
        sendto(sfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, len);


        // 接受服务器的处理信息
        struct sockaddr_in peer;
        socklen_t len_peer = sizeof(struct sockaddr_in);
        ssize_t n = recvfrom(sfd, buffer, BUF_SIZE - 1, 0, (struct sockaddr*)&peer, &len_peer);
        if(n < 0)
            perror("client recvfrom");
        buffer[n] = 0;
        std::cout << "server echo# " << buffer << std::endl;
    } 

    return 0;
}
